package com.lwj.framework.security;

import java.io.UnsupportedEncodingException;
import java.util.Map;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import com.lwj.framework.util.ServletUtil;
import com.lwj.framework.util.Utils;
import com.lwj.framework.entity.AuthEntity;
import com.lwj.framework.entity.AuthProperties;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class AuthUtils {
	private static final Logger logger = LoggerFactory.getLogger(AuthUtils.class);

	public static final String authorization_code_grantType = "authorization_code";
	public static final String implicit_grantType = "implicit";
	public static final String client_credentials_grantType = "client_credentials";
	public static final String password_grantType = "password";
	public static final String refresh_token_grantType = "refresh_token";

	public static final String ROLE_CLIENT = "ROLE_CLIENT";
	public static final String ROLE_TRUSTED_CLIENT = "ROLE_TRUSTED_CLIENT";

	public static final String INTERIOR_CLIENT = "interior";

	/** 是否存储token */
	public static final String isStore = "ist";
	public static final Integer False = 0;
	public static final Integer True = 1;
	/** 自定义授权 */
	public static final String Iauthorization = "iauthorization";
	/** 自定义授权信息 */
	public static final String authinfo = "authinfo";

	public static final String TOKEN_STORE = "tokenStore";

	private static Pattern storePattern = null;
	private static volatile Base64 base64=null;

	public static boolean isStore(String token) {
		String json = decodeBody(token);
		if (storePattern == null) {
			synchronized (AuthUtils.class) {
				if (storePattern == null) {
					try {
						storePattern = Pattern.compile(isStoreRegex());
					} catch (Exception e) {
					}
				}
			}
		}
		boolean store = storePattern.matcher(json).find();
		return store;
	}

	public static boolean isStoreClient(String clientId, AuthProperties authProperties) {
		boolean store = false;
		AuthEntity authEntity = authProperties.getAuthById(clientId);
		if (authEntity != null) {
			store = authEntity.getTokenStore();
		}
		return store;
	}

	/**
	 * 读取token的map
	 *
	 * @param token
	 * @return
	 */
	public static Map<String, Object> tokenMap(String token) {
		String json = decodeBody(token);
		return Utils.jsonToMap(json);
	}

	public static String isStoreRegex() {
		StringBuilder regex = new StringBuilder();
		regex.append("(.*\"").append(AuthUtils.isStore).append("\":").append(AuthUtils.True).append(".*)");
		return regex.toString();
	}
    public static Base64 getBase64(){
		if(base64==null){
			synchronized (AuthUtils.class){
				if(base64==null){
					base64=new Base64();
				}
			}
		}
		return base64;
	}
	private static String decodeBody(String token) {
		String json = null;
		try {
			String[] split = token.split("\\.");
			byte[] bytes = getBase64().decode(split[1]);
			json = new String(bytes, "utf-8");
		} catch (UnsupportedEncodingException e) {
			logger.error("token exception", e);
		}
		return json;
	}

	/**
	 * 读取授权信息
	 *
	 * @return
	 */
	public static AuthEntity getIauthorization() {
		return (AuthEntity) ServletUtil.getRequest().getAttribute(AuthUtils.Iauthorization);
	}

	/**
	 * 读取授权信息
	 *
	 * @param request
	 * @return
	 */
	public static AuthEntity getIauthorization(HttpServletRequest request) {
		return (AuthEntity) request.getAttribute(AuthUtils.Iauthorization);
	}

}
